<script setup lang="ts">
import {
  ElButton,
  ElTable,
  ElTableColumn,
  ElInput,
  ElInputNumber,
  TableColumnCtx
} from 'element-plus'
import 'element-plus/es/components/icon/style/css'
import 'element-plus/es/components/input/style/css'
import 'element-plus/es/components/button/style/css'
import 'element-plus/es/components/tag/style/css'
import 'element-plus/es/components/menu/style/css'
import 'element-plus/es/components/menu-item/style/css'
import { PropType, reactive, ref, watch, h, onMounted, nextTick } from 'vue'
import { useTableDialogStore } from '@/store/modules/purchaseTableDialog'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { useForm } from '@/hooks/web/useForm'
import { getOrderSelectApi, getProductSelectApi } from '@/api/purchase'
import { processingAccuracy } from '@/utils'
import { useI18n } from 'vue-i18n'

const { t } = useI18n()

const { formMethods } = useForm()
const { getFormData, getElFormExpose } = formMethods

type tableDataType = {
  order_id: number | null
  order_no: string
  id: number
  cname: string
  code: string
  style_code: string
  unit: string
  num: number
  unit_price: number
  unit_sum: number
  notes: string
}

interface SummaryMethodProps<T = tableDataType> {
  columns: TableColumnCtx<T>[]
  data: T[]
}

const props = defineProps({
  tableDialogStoreID: {
    type: String,
    default: ''
  },
  tableDialogCurdSchema: {
    type: Array as PropType<CrudSchema[]>, // 明确类型为 CrudSchema[]
    default: () => [] // 设置默认值为一个空数组
  },
  modelValue: {
    type: Array as PropType<tableDataType[]>,
    default: () => []
  },
  disabled: {
    type: Boolean,
    default: () => false
  },
  setValues: {
    type: Function,
    default: () => {}
  },
  // 新增的修改模式参数
  editMode: {
    type: Boolean,
    default: false
  },
  getCurrentFormData: {
    type: Function,
    default: () => ({})
  }
})

// 挂载完成时触发
onMounted(() => {
  initializeData()

  // 延迟再次尝试获取数据，以防表单数据还没有完全加载
  // if (props.editMode) {
  //   setTimeout(() => {
  //     console.log('延迟初始化')
  //     initializeData()
  //   }, 100)

  //   setTimeout(() => {
  //     console.log('再次延迟初始化')
  //     initializeData()
  //   }, 500)
  // }
})

const emit = defineEmits(['update:modelValue'])

const tableDialogStore = useTableDialogStore(props.tableDialogStoreID)
const { allSchemas } = useCrudSchemas(
  props.tableDialogCurdSchema ? props.tableDialogCurdSchema : []
)
const tableData = ref<tableDataType[]>([])

// 初始化数据，处理修改模式
const initializeData = async () => {
  if (props.editMode && props.getCurrentFormData) {
    // 尝试获取当前表单数据
    try {
      const formDataResult = props.getCurrentFormData()

      // 检查是否是 Promise
      const formData =
        formDataResult && typeof formDataResult.then === 'function'
          ? await formDataResult
          : formDataResult

      if (formData && typeof formData === 'object') {
        // 提取 order_id 和 sales_orderno
        if (formData.order_id) {
          formOrderId.value = formData.order_id
        }

        if (formData.sales_orderno) {
          formSalesOrderNo.value = formData.sales_orderno
          order_no.value = formData.sales_orderno
        }
      }
    } catch (error) {
      console.warn('获取表单数据失败:', error)
    }
  }
}

const addEmptyRow = () => {
  tableDialogStore.selectedItems = []
  tableDialogStore.openDialog()
  tableDialogStore.setSchema(allSchemas)
}

const rowClassName = ({ row }) => (row.editing ? 'editing-row' : '')
const editCell = (row) => {
  row.editing = true
}

const submit = async () => {
  const elForm = await getElFormExpose()
  const valid = await elForm?.validate().catch((err) => {
    console.log('err', err)
  })
  if (valid) {
    const formData = await getFormData()
    formData.pid = tableDialogStore.selectedItems.map((item) => item.id).join(',')
    return formData
  }
}
const removeRow = (row, index) => {
  // tableDialogStore.selectedItems = tableDialogStore.selectedItems.filter(
  //   (item: SelectedItem) => item.id !== row.id
  // )
  order_no.value = ''
  tableDialogStore.removeItem(row.id)
  tableData.value.splice(index, 1)
}

defineExpose({
  submit
})

tableDialogStore.dialogSubmit = () => {
  // const existingIds = new Set(tableData.value.map((item) => item.id))
  // 允许重复添加商品
  tableDialogStore.selectionRow.forEach((item) => {
    if (item.id) {
      tableData.value.push({
        order_id: null,
        order_no: '',
        id: item.id,
        cname: item.cname,
        code: item.code,
        style_code: item.style_code,
        unit: item.unit_value,
        num: 0,
        unit_price: 0,
        unit_sum: 0,
        notes: ''
      })
    }
  })
}
const unitSums = reactive({})
const isDisabled = ref(props.disabled)
const order_no = ref<string>()

// 添加状态来存储表单中的 order_id 和 sales_orderno
const formOrderId = ref<string | number>('')
const formSalesOrderNo = ref<string>('')

const orderList = ref<Array<Record<string, any>>>([])
const selectLoading = ref<boolean>(false)

// 创建一个增强版的 setValues 函数来捕获这些值
const enhancedSetValues = (values: any) => {
  if (values.order_id !== undefined) {
    formOrderId.value = values.order_id
  }
  if (values.sales_orderno !== undefined) {
    formSalesOrderNo.value = values.sales_orderno
    order_no.value = values.sales_orderno
  }

  // 调用原始的 setValues
  props.setValues(values)
}

// 暴露增强版的 setValues 给内部使用
const internalSetValues = enhancedSetValues

/**
 * 获取订单列表
 * @param value
 */
const getOrderOptions = async (value) => {
  if (value) {
    selectLoading.value = true
    const userResp = await getOrderSelectApi({ order_no: value })
    orderList.value = userResp.data
    selectLoading.value = false
  }
}

const changeOrder = async (row, item) => {
  if (!row) return
  // tableData.value = []
  const userResp = await getProductSelectApi({ order_id: row.value })

  // 添加安全检查，确保 userResp.data 和 userResp.data.list 存在
  if (userResp?.data?.list && Array.isArray(userResp.data.list)) {
    userResp.data.list.forEach((item) => {
      tableData.value.push({
        order_id: row.value,
        order_no: row.label,
        id: item.id,
        cname: item.cname,
        code: item.code,
        style_code: item.style_code,
        unit: item.unit_value,
        num: item.quantity,
        unit_price: 0,
        unit_sum: 0,
        notes: ''
      })
    })
  } else {
    console.warn('getProductSelectApi 返回的数据格式不正确:', userResp)
  }

  internalSetValues({
    sales_orderno: row.label,
    order_id: row.value
  })
}

const getSummaries = (param: SummaryMethodProps) => {
  const needHandleColumns = ['num', 'unit_price', 'unit_sum']
  // const needShowMoney = ['unit_price', 'unit_sum']
  const needShowMoney: string[] = []
  const { columns, data } = param
  const sums: string[] = []
  let pay_amount = 0
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index.toString()] = h('div', { style: { textDecoration: 'underline' } }, ['Total Cost'])
      return
    }
    const values = data.map((item) => Number(item[column.property]))
    if (
      !values.every((value) => Number.isNaN(value)) &&
      needHandleColumns.includes(column.property)
    ) {
      sums[index] = `${needShowMoney.includes(column.property) ? '¥' : ''} ${values.reduce(
        (prev, curr) => {
          const value = Number(curr)
          if (!Number.isNaN(value)) {
            return prev + curr
          } else {
            return prev
          }
        },
        0
      )}`
    } else {
      sums[index] = 'N/A'
    }

    if (column.property == 'unit_sum') {
      pay_amount = values.reduce((prev, curr) => {
        const value = Number(curr)
        if (!Number.isNaN(value)) {
          return prev + curr
        } else {
          return prev
        }
      }, 0)
    }
  })
  nextTick(() => {
    internalSetValues({
      product_total_amount: pay_amount
    })
  })
  return sums
}

watch(
  tableData,
  (newTableData) => {
    // 清空 unitSums
    Object.keys(unitSums).forEach((key) => delete unitSums[key])

    // 更新 unitSums
    newTableData.forEach((row, index) => {
      unitSums[index] = processingAccuracy(row.num * row.unit_price)
      row.unit_sum = unitSums[index]
    })
    // 更新表单数据
    emit('update:modelValue', newTableData)
  },
  { deep: true }
)

watch(
  () => props.modelValue,
  (val: any) => {
    tableData.value = val
  },
  {
    deep: true,
    immediate: true
  }
)

// 监听表单中的 order_id 和 sales_orderno 变化
watch(
  [formOrderId, formSalesOrderNo],
  ([newOrderId, newSalesOrderNo]) => {
    if (newSalesOrderNo && newSalesOrderNo !== order_no.value) {
      order_no.value = newSalesOrderNo
      console.log('设置订单号:', newSalesOrderNo)
    }
  },
  { deep: true }
)
</script>

<template>
  <div>
    <!--    <el-form-item label="销售订单编号" v-show="!isDisabled">-->
    <el-select
      v-show="!isDisabled"
      v-model="order_no"
      :placeholder="t('common.inputText') + t('order.orderCode')"
      :filterable="true"
      :multiple="false"
      :clearable="true"
      :remote="true"
      :remote-method="getOrderOptions"
      :loading="selectLoading"
      style="width: 250px; margin-left: 0"
      @change="changeOrder"
    >
      <el-option v-for="item in orderList" :key="item.value" :label="item.label" :value="item" />
    </el-select>
    <br />
    <!--    </el-form-item>-->
    <el-button type="primary" :disabled="isDisabled" @click="addEmptyRow">{{
      t('action.increase')
    }}</el-button>
    <el-table
      :data="tableData"
      border
      show-summary
      :summary-method="getSummaries"
      style="width: 100%; margin-top: 10px"
      :row-class-name="rowClassName"
      @cell-click="editCell"
    >
      <!-- 订单ID -->
      <el-table-column prop="order_no" :label="t('order.orderCode')">
        <template #default="{ row }">
          <span>{{ row.order_no }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="cname" :label="t('product.cname')">
        <template #default="{ row }">
          <span>{{ row.cname }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="code" :label="t('product.code')">
        <template #default="{ row }">
          <span>{{ row.code }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="style_code" :label="t('product.style_code')">
        <template #default="{ row }">
          <span>{{ row.style_code }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="unit" :label="t('purchase.purchase_unit')">
        <template #default="{ row }">
          <span>{{ row.unit }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="num" :label="t('order.quantity')" width="180">
        <template #default="{ row }">
          <!-- 添加条件判断 -->
          <div style="display: flex; justify-content: center; align-items: center">
            <ElInputNumber :disabled="isDisabled" v-model="row.num" :min="1" type="number" />
          </div>
          <!-- <span v-else-if="row">{{ row.num }}</span>-->
        </template>
      </el-table-column>
      <el-table-column prop="unit_price" :label="t('purchase.purchase_price')">
        <template #default="{ row }">
          <el-input :disabled="isDisabled" v-model="row.unit_price" />
        </template>
      </el-table-column>
      <el-table-column prop="unit_sum" :label="t('purchase.unit_sum')">
        <template #default="{ row }">
          <el-input disabled v-model="row.unit_sum" />
        </template>
      </el-table-column>
      <el-table-column prop="notes" :label="t('common.remark')">
        <template #default="{ row }">
          <el-input :disabled="isDisabled" v-model="row.notes" />
        </template>
      </el-table-column>
      <el-table-column fixed="right" :label="t('common.operation')" width="100">
        <template #default="scope">
          <ElButton
            class="input-button"
            size="small"
            type="primary"
            plain
            link
            :disabled="isDisabled"
            @click.prevent="removeRow(scope.row, scope.$index)"
          >
            {{ t('action.del') }}
          </ElButton>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<style scoped>
.editing-row {
  background-color: #f5f7fa;
}
</style>
